package com.front.web.lvyouFood;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.utils.EmojiUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.lvyou.domain.LvyouMember;
import com.bootdo.lvyou.domain.XcxConfig;
import com.front.web.wx.utils.XiaoChengXuUtils;
import org.apache.commons.codec.digest.DigestUtils;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/f/lvyou/MemberApiController")
public class MemberApiController extends BaseFoodShopController{



    /**
     * 得到openId
     * localhost:8090/f/lvyou/MemberApiController/getOpenId?code=13456
     * 保存
     */
    @RequestMapping("getOpenId")
    public R getOpenId(@RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response){

        List<XcxConfig> list = xcxConfigService.list(new HashMap<>());
        XcxConfig xcxConfig = list.get(0);
        JSONObject json = XiaoChengXuUtils.getOpenId(xcxConfig.getAppId(),xcxConfig.getAppSecret(),code);
        if(json.containsKey("openid") && json.containsKey("session_key")) {
            String  openId  = json.getString("openid");
            String  sessionKey  = json.getString("sessionKey");
            LvyouMember lvyouMember = lvyouMemberService.getByOpenid(openId);
            if(null == lvyouMember){
                lvyouMember = new LvyouMember();
                lvyouMember.setOpenid(openId);
                lvyouMember.setIsShow(1);
                lvyouMember.setIsShow(1);
                lvyouMemberService.save(lvyouMember);
            }
            return R.ok().put("openId", openId).put("sessionKey", sessionKey).put("userInfo",lvyouMember);
        }else {
            return R.error();
        }
    }

    /**
     * 保存用户信息
     *          localhost:8090/f/lvyou/MemberApiController/saveMemberInfo?nickName=13456&avatar=&gender=&openId=
     * @param nickName
     * @param avatarUrl
     * @param gender
     * @param openId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("saveMemberInfo")
    public R saveMemberInfo(@RequestParam("nickName") String nickName,
                            @RequestParam("avatar") String avatarUrl,
                            @RequestParam("gender") Integer gender ,
                            @RequestParam("openid") String  openId ,
                            HttpServletRequest request, HttpServletResponse response){
        LvyouMember  member =  lvyouMemberService.getByOpenid(openId);
        if(null == member){
            return R.error("会员不存在");
        }
        member.setNickname(EmojiUtils.emojiChange(nickName));
        if(com.alibaba.druid.util.StringUtils.isEmpty(member.getAvatar())){
            member.setAvatar(avatarUrl);
        }

        if(null != gender){
            if(gender.equals(0)){
                member.setSex("未知");
            }else
            if(gender.equals(1)){
                member.setSex("男");
            } else if(gender.equals(2)){
                member.setSex("女");
            }
        }
        lvyouMemberService.save(member);
        return R.ok();

    }

    /**
     * 微信注册 绑定手机号
     *                      localhost:8090/f/lvyou/MemberApiController/WxRegister?mobile=13456&code=&openid=
     * @param mobile
     * @param code
     * @param openid
     * @return
     */
    @RequestMapping("WxRegister")
    public R register(@RequestParam(value = "mobile",defaultValue = "")String mobile,
                      @RequestParam(value = "realName",defaultValue = "")String realName,
                      @RequestParam(value = "idCard",defaultValue = "")String idCard,
                      @RequestParam(value = "code",defaultValue = "")String code,
                      @RequestParam("nickName") String nickName,
                      @RequestParam("avatar") String avatarUrl,
                      @RequestParam("gender") Integer gender ,
                      @RequestParam(value = "openid",defaultValue = "")String openid){
        if(StringUtils.isBlank(mobile)){
            return R.error("请填写手机号");
        }

        if(StringUtils.isBlank(code)){
            return R.error("请填写验证码");
        }

        if(StringUtils.isBlank(realName)){
            return R.error("请填写真实姓名");
        }
        if(StringUtils.isBlank(idCard)){
            return R.error("请填写身份证号码");
        }

        if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
            return R.error("验证码错误!");
        }


        LvyouMember lvyouMember = lvyouMemberService.getByOpenid(openid);
        if(lvyouMember==null){
            lvyouMember=new LvyouMember();
        }
        if(lvyouMember==null){
            return R.error("请先授权登录");
        }
        lvyouMember.setNickname(EmojiUtils.emojiChange(nickName));
        if(com.alibaba.druid.util.StringUtils.isEmpty(lvyouMember.getAvatar())){
            lvyouMember.setAvatar(avatarUrl);
        }
        if(null != gender){
            if(gender.equals(0)){
                lvyouMember.setSex("未知");
            }else
            if(gender.equals(1)){
                lvyouMember.setSex("男");
            } else if(gender.equals(2)){
                lvyouMember.setSex("女");
            }
        }
        lvyouMember.setRealName(realName);
        lvyouMember.setMobile(mobile);
        lvyouMember.setIdCard(idCard);
        lvyouMember.setIsShow(1);//1 代表正常
        lvyouMemberService.save(lvyouMember);

        return R.ok("绑定手机号成功");
    }


    /**
     * 设置登录密码       localhost:8090/f/lvyou/MemberApiController/setPassword?mobile=13456&code=&memberId=&newPassword=
     * @return
     */
    @RequestMapping("setPassword")
    public R setPassword(@RequestParam(value = "mobile",defaultValue = "") String mobile,
                         @RequestParam(value = "memberId",defaultValue = "") Long memberId,
                         @RequestParam(value = "code",defaultValue = "") String code,
                         @RequestParam(value = "newPassword",defaultValue = "") String newPassword){
        LvyouMember lvyouMember = lvyouMemberService.get(memberId);
        HashMap<String, Object> param = new HashMap<>();
        param.put("mobile",mobile);
        param.put("id",memberId);
        List<LvyouMember> list = lvyouMemberService.list(param);
        if(list.size()==0||list==null){
            return R.error("手机号码与绑定不符");
        }
        if(lvyouMember==null){
            return R.error("请登录后再操作");
        }
        if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
            return R.error("验证码错误!");
        }
        lvyouMember.setPassword(DigestUtils.sha256Hex(newPassword));

        lvyouMemberService.save(lvyouMember);
        return R.ok("设置密码成功");
    }
    /**
     * APP注册
     * @param mobile
     * @param code
     * @param sex
     * @param age
     * @param nickname
     * @param password
     * @param systemType
     * @return
     */
    @RequestMapping("APPRegister")
    public R register(@RequestParam(value = "mobile",defaultValue = "")String mobile,
                      @RequestParam(value = "code",defaultValue = "")String code,
                      @RequestParam(value = "sex",defaultValue = "")String sex,
                      @RequestParam(value="age",defaultValue = "age")Integer age,
                      @RequestParam(value="nickname",defaultValue = "游客")String nickname,
                      @RequestParam(value="password",defaultValue = "")String password,
                      @RequestParam(value="systemType",defaultValue = "")String systemType){

        if(StringUtils.isBlank(mobile)){
            return R.error("请填写手机号");
        }
        LvyouMember byMobile = lvyouMemberService.getByMobile(mobile);
        if(byMobile!=null){
            return R.error("该号码已经注册，请登录");
        }



        if(StringUtils.isBlank(code)){
            return R.error("请填写验证码");
        }
        if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
            return R.error("验证码错误!");
        }
        try {
            LvyouMember lvyouMember = new LvyouMember();
            lvyouMember.setMobile(mobile);
            lvyouMember.setAge(age);
            lvyouMember.setMobileType(systemType);
            lvyouMember.setNickname(nickname);
            lvyouMember.setSex(sex);
            lvyouMember.setPassword(DigestUtils.sha256Hex(password));
            lvyouMember.setIsShow(0);//0 代表正常
            lvyouMemberService.save(lvyouMember);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("注册失败");
        }
        return R.ok("注册成功");
    }

    /**
     *  通过 电话号加验证码 或者  电话号加密码登录
     *                                  localhost:8090/f/lvyou/MemberApiController/login?mobile=13456&code=&password=
     * @param mobile
     * @param code
     * @param password
     * @return
     */
    @RequestMapping("login")
    public R login(@RequestParam(value = "mobile",defaultValue = "") String mobile,
                   @RequestParam(value = "code",defaultValue = "") String code,
                   @RequestParam(value = "password",defaultValue = "") String password){
        if(StringUtils.isBlank(mobile)){
            return R.error("请填写手机号");
        }

        LvyouMember lvyouMember=lvyouMemberService.getByMobile(mobile);
        if(lvyouMember==null){
            return R.error("还未注册，请注册后再登录");
        }
        if(StringUtils.isNotBlank(code)){//使用验证码进行登录
            if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
                return R.error("验证码错误!");
            }else {
                LvyouMember lvyouMember1 = lvyouMemberService.getByMobile(mobile);
                //进行Redis 缓存处理
                JedisUtils.set(DigestUtils.sha256Hex(mobile), JSON.toJSONString(lvyouMember1), 60*60*24*20);
                return R.ok().put("l",lvyouMember1);
            }
        }else{

            LvyouMember member = lvyouMemberService.login(mobile,password);
            if (null == member) {
                return R.error("账号或者密码错误");
            }
            // 进行redis 的缓存处理
            JedisUtils.set(DigestUtils.sha256Hex(mobile), JSON.toJSONString(member), 60*60*24*20);
             return R.ok().put("l",member);

        }


    }


    /**
     *   设置购票人 联系方式 以及联系人
     * @param realName
     * @param idCard
     * @param contactMobile
     * @param memberId
     * @return
     */
    @RequestMapping("setTicketContact")
    public R setTicketContact(@RequestParam(value = "realName",defaultValue ="" )String realName,
                              @RequestParam(value = "idCard",defaultValue ="" )String idCard,
                              @RequestParam(value = "contactMobile",defaultValue ="" )String contactMobile,
                              @RequestParam(value = "memberId",defaultValue = "")Long memberId){

        LvyouMember lvyouMember = lvyouMemberService.get(memberId);
        lvyouMember.setRealName(realName);
        lvyouMember.setIdCard(idCard);
        lvyouMember.setContactMobile(contactMobile);

        lvyouMemberService.save(lvyouMember);

        return R.ok().put("l",lvyouMember);
    }
}
